<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use Dompdf\Dompdf;
use Dompdf\Options;
use think\facade\Db;

class Test extends Command
{
    protected $authTable = 'pwinerp_auth_rule';
    protected $navTable = 'pwinerp_admin_nav';
    protected function configure()
    {
        // 指令配置
        $this->setName('test')
            ->setDescription('the test command');
    }


    protected function execute(Input $input, Output $output)
    {
        $this->test();
//        $this->navRule();
//        $this->pathRule();
//        $this->extraGroup();

        // 指令输出
        $output->writeln('test');
    }

    public function test(){
        $time = time();
        $url = 'https://imgsc.xjcerp.com/zfdasgq_71347.xlsx';
        file_put_contents("./aaa.xlsx");
        var_dump(time()-$time);
    }

    // 通过文件给auth设置菜单属性
    public function pathRule(){
        $directory = './public/tpl/Admin';
        $files = $this->traverseDirectory($directory);
        $this->pathRuleAbsolute($files);
        $this->pathRuleLocation($files);
        $this->pathRuleHref($files);
        $this->pathRuleAbsolute($files,true);
    }

    /**
     * 绝对匹配
     * @param $files
     * @return void
     */
    public function pathRuleAbsolute($files,$isOrigin = false){

        $authList = Db::table($this->authTable)->where(['nav_id'=>0])->select()->toArray();
        foreach ($files as $file) {
            $originContent = file_get_contents($file);
            if(!$isOrigin){
                $content = preg_replace('/href=[\'|"].*[\'|"]/',"",$originContent);
            }else{
                $content = $originContent;
            }

            foreach($authList as $authRow){
                $route = str_replace(['./public/tpl/','.html'],['',''],$file);
                $authName = $authRow['name'];
                $matchStringHaveGangAndAdmin = str_replace("/","\/","/".$authName);
                $matchStringHaveAdmin = str_replace("/","\/",$authName);
                $matchStringNoAdmin = str_replace(["Admin","/Admin"],["",""],$authName);
                $matchStringNoAdmin = str_replace("/","\/",$matchStringNoAdmin);
                $matchString = $this->matchRule("/".$matchStringHaveAdmin."/",$content,$route,$authRow);
                if(empty($matchString)){
                    $matchString = $this->matchRule("/".$matchStringNoAdmin."/",$content,$route,$authRow);
                }
                if(empty($matchString)){
                    $matchString = $this->matchRule("/".$matchStringHaveGangAndAdmin."/",$content,$route,$authRow);
                }
            }
        }
    }

    /**
     * location匹配
     * @param $files
     * @return void
     */
    public function pathRuleLocation($files){
        $authList = Db::table($this->authTable)->where(['nav_id'=>0])->order("id asc")->select()->toArray();
        foreach ($files as $file) {
            $originContent = file_get_contents($file);
            foreach($authList as $authRow){
                $route = str_replace(['./public/tpl/','.html'],['',''],$file);
                $authName = $authRow['name'];
                $matchStringHaveGangAndAdmin = str_replace("/","\/","/".$authName);
                $matchStringHaveAdmin = str_replace("/","\/",$authName);
                $matchStringNoAdmin = str_replace(["Admin","/Admin"],["",""],$authName);
                $matchStringNoAdmin = str_replace("/","\/",$matchStringNoAdmin);
                $matchString = $this->matchRule('/location=([\'|\"]){:U\([\'|\"]'.$matchStringHaveAdmin.'[\'|\"]/i',$originContent,$route,$authRow);
                if(empty($matchString)){
                    $matchString = $this->matchRule('/location=([\'|\"]){:U\([\'|\"]'.$matchStringNoAdmin.'[\'|\"]/i',$originContent,$route,$authRow);
                }
                if(empty($matchString)){
                    $matchString = $this->matchRule('/location=([\'|\"]){:U\([\'|\"]'.$matchStringHaveGangAndAdmin.'[\'|\"]/i',$originContent,$route,$authRow);
                }
            }
        }
    }
    /**
     * href匹配
     * @param $files
     * @return void
     */
    public function pathRuleHref($files){
        $authList = Db::table($this->authTable)->where(['nav_id'=>0])->order("id asc")->select()->toArray();
        foreach ($files as $file) {
            $originContent = file_get_contents($file);
            foreach($authList as $authRow){
                $route = str_replace(['./public/tpl/','.html'],['',''],$file);
                $authName = $authRow['name'];
                $matchStringHaveGangAndAdmin = str_replace("/","\/","/".$authName);
                $matchStringHaveAdmin = str_replace("/","\/",$authName);
                $matchStringNoAdmin = str_replace(["Admin","/Admin"],["",""],$authName);
                $matchStringNoAdmin = str_replace("/","\/",$matchStringNoAdmin);
                $matchString = $this->matchRule('/href=([\'|\"]){:U\([\'|\"]'.$matchStringHaveAdmin.'[\'|\"]/i',$originContent,$route,$authRow);
                if(empty($matchString)){
                    $matchString = $this->matchRule('/href=([\'|\"]){:U\([\'|\"]'.$matchStringNoAdmin.'[\'|\"]/i',$originContent,$route,$authRow);
                }
                if(empty($matchString)){
                    $matchString = $this->matchRule('/href=([\'|\"]){:U\([\'|\"]'.$matchStringHaveGangAndAdmin.'[\'|\"]/i',$originContent,$route,$authRow);
                }
                if(empty($matchString)){
                    $matchString = $this->matchRule('/href=([\'|\"])'.$matchStringHaveGangAndAdmin.'[\'|\"]/i',$originContent,$route,$authRow);
                }
                if(empty($matchString)){
                    $matchString = $this->matchRule('/href=([\'|\"])'.$matchStringHaveGangAndAdmin.'\/[\'|\"]/i',$originContent,$route,$authRow);
//                    if($authName == 'Admin/InStorage/returns'){
//                        var_dump($matchStringHaveGangAndAdmin);
//                        die("qqq");
//                    }
                }
            }
        }
    }
    public function extraGroup(){
        $this->matchIndex(); //index匹配
        $this->matchMap(); //按照字典分配
    }

    /**
     * 分组匹配按照字典
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function matchMap(){
        $group = [];
        $authList = Db::table($this->authTable)->where(['nav_id'=>0])->order("id asc")->select()->toArray();
        foreach($authList as $value){
            $authName = $value['name'];
            $authNameArr = explode("/",$authName);
            $groupKey = implode('/',[$authNameArr[0],$authNameArr[1]]);
            $group[strtolower($groupKey)][] = $value;
        }
        var_dump(array_keys($group));
        $map = $this->extraAuthMap();
        if(!empty($group)){
            foreach($group as $key=>$value){
                if(!empty($map[$key])){
                    $navRow = Db::table($this->navTable)->where(['mca'=>$map[$key]])->find();
                    if(!empty($navRow)){
                        Db::table($this->authTable)->where([['id','in',array_column($value,'id')]])->update(['nav_id'=>$navRow['id']]);
                    }
                }
            }
        }
    }
    public function extraAuthMap(){
        return  [
            'admin/shownav'=>'Admin/Nav/index',
            'admin/instorage'=>'Admin/InStorage/instorage',
            'admin/warehouse'=>'Admin/Warehouse/warehouselist',
            'admin/develop'=>'Admin/Storages/designDevelopApplyList',
            'admin/amazonfulfillorder'=>'Admin/AmazonFulfillorder/orderlist',
            'admin/tasks'=>'Admin/Tasks/gmoevent',
            'admin/overseas'=>'Admin/Overseas/summary',
            'admin/stockup'=>'Admin/StockUp/stockUpPreApplyList',
            'admin/spusupplierprice'=>'Admin/Storages/designDevelopApplyList',
            'admin/goods'=>'Admin/Products/index',
            'admin/index'=>'Admin/Index/dataBoard',
            'admin/datastatistics'=>'Admin/Index/dataBoard',
            'admin/rewarded'=>'Admin/Rewarded/departmentlist',
            'admin/temu'=>'Admin/Goods/temu_library',

            'admin/logistics'=>'Admin/Logistics/provider',
            'admin/finance'=>'Admin/Finance/turnover',
            'admin/statements'=>'Admin/Index/dataBoard',
            'admin/common'=>'Admin/Config/indexNew',
            'admin/performance'=>'Admin/Performance/amazonPerformanceArmysList',
            'admin/spugroup'=>'Admin/Storages/designDevelopApplyList',

            'admin/platform'=>'Admin/Platform/amazon',
            'admin/applypurchase'=>'Admin/ApplyDeliver/index',
            'admin/print'=>'Admin/Logistics/FreightTrial'

        ];
    }

    /**
     * 分组匹配index
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function matchIndex(){
        $group = [];
        $authList = Db::table($this->authTable)->where(['nav_id'=>0])->order("id asc")->select()->toArray();
        foreach($authList as $value){
            $authName = $value['name'];
            $authNameArr = explode("/",$authName);
            $groupKey = implode('/',[$authNameArr[0],$authNameArr[1]]);
            $group[strtolower($groupKey)][] = $value;
        }
        if(!empty($group)){
            foreach($group as $key=>$value){
                $navRow = Db::table($this->navTable)->where(['mca'=>$key.'/index'])->find();
                if(!empty($navRow)){
                    Db::table($this->authTable)->where([['id','in',array_column($value,'id')]])->update(['nav_id'=>$navRow['id']]);
                }
            }
        }
    }
    public function matchRule($preg,$content,$route,$authRow){
        $res = '';
        preg_match($preg,$content,$matchRes);
//        if($authRow['name'] == 'Admin/InStorage/returns'){
//            var_dump($preg);
//            var_dump($matchRes);
//            var_dump($content);
//            die();
//        }

        if(!empty($matchRes[0])){
            $res = $matchRes[0];
            $authRowFind = Db::table($this->authTable)->where(['id'=>$authRow['id']])->find();
            if(empty($authRowFind['nav_id'])){
                $navRow = Db::table($this->navTable)->where(['mca'=>$route])->find();
                if(!empty($navRow)){ //这里后面为空取index
                    Db::table($this->authTable)->where(['id'=>$authRow['id']])->update(['nav_id'=>$navRow['id']]);
                }else{
                    $routeArr = explode('/',$route);
                    $routeArr[2] = 'index';
                    $route = implode('/',$routeArr);
                    $navRow = Db::table($this->navTable)->where(['mca'=>$route])->find();
                    if(!empty($navRow)){
                        Db::table($this->authTable)->where(['id'=>$authRow['id']])->update(['nav_id'=>$navRow['id']]);
                    }else{
                        var_dump($route);
                    }
                }
            }
        }
        return $res;
    }

    public function navRule(){
        $firsList = Db::table($this->navTable)->where(['pid'=>0])->select()->toArray();
        $secondList =  Db::table($this->navTable)->where([['pid','in',array_column($firsList,'id')]])->select()->toArray();
        $thirdList =  Db::table($this->navTable)->where([['pid','in',array_column($secondList,'id')]])->select()->toArray();
        foreach($thirdList as $third){
//            var_dump($third);
            $authRow = Db::table($this->authTable)->where(['name'=>$third['mca']])->find();
            if(!empty($authRow)){
                var_dump($third['id']);
                Db::table($this->authTable)->where(['id'=>$authRow['id']])->update(['nav_id'=>$third['id'],'sort'=>1,'title'=>$third['name']]);
            }
        }
    }


    public function traverseDirectory($dir) {
        $files = [];

        $items = scandir($dir);

        foreach ($items as $item) {
            if ($item == '.' || $item == '..') {
                continue;
            }

            $path = $dir . '/' . $item;

            if (is_file($path)) {
                $files[] = $path;
            } elseif (is_dir($path)) {
                $subFiles = $this->traverseDirectory($path);
                $files = array_merge($files, $subFiles);
            }
        }

        return $files;
    }



}
